package com.example.uupaymuch.controller.notice.uupay;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UuPayComponent {

//    private final String noticePay = "https://api.58le.com/api/pay/notify/brazilpay/uupay";
    private final String noticePay = "http://localhost:27003/api/pay/notify/brazilpay/uupay";
    private static final String HMAC_SECRET = "123456789"; // 从安全配置中获取
    private final CloseableHttpClient httpClient;

    public UuPayComponent() {
        // 创建带有连接池的 HttpClient 实例
        this.httpClient = HttpClients.custom()
                .setMaxConnTotal(200)  // 设置最大连接数
                .setMaxConnPerRoute(200)  // 设置每个路由的最大连接数
                .build();
    }

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer =
            new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2);

    public void doNotifyPay(Map<String, Object> noticeMap, String notifyUrl) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentPay(noticeMap, notifyUrl);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void notifyPaymentPay(Map<String, Object> noticeMap, String notifyUrl) throws IOException {
        Map<String, Object> params = new HashMap<>(noticeMap);

        try {
            if (StringUtils.isNotEmpty(notifyUrl)){
                notifyUrl = noticePay;
            }
            HttpPost request = new HttpPost(notifyUrl);
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);


            CloseableHttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("Failed to notify payment. HTTP Status: {}", statusCode);
            }

        } catch (IOException e) {
            log.error("Error serializing JSON: {}", e.getMessage());
            throw e; // 重新抛出以便上层处理
        }
    }

}
